package com.example.littleken.ormlite_text.adapter;

import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.example.littleken.ormlite_text.Activity.MainActivity;
import com.example.littleken.ormlite_text.R;
import com.example.littleken.ormlite_text.Utils.Utils;
import com.example.littleken.ormlite_text.bean.LifeDiary;

import java.util.List;

/**listView适配器
 * Created by littleken on 2018/6/15.
 */

public class lifediaryListViewAdapter extends BaseAdapter {
    //数据源
    List<LifeDiary> lifeDiaries;
    //反射器，反射布局
    LayoutInflater inflater;
    //初始化反射器
    public lifediaryListViewAdapter(Context context) {
        this.inflater = LayoutInflater.from(context);
    }
    //设置数据源
    public void setlifediary(List<LifeDiary> lifeDiaries) {
        this.lifeDiaries = lifeDiaries;
    }
    //无参构造
    public lifediaryListViewAdapter() {
    }

    @Override
    public int getCount() {
      return  (lifeDiaries==null)?0:lifeDiaries.size();
    }

    @Override
    public Object getItem(int i) {
        return lifeDiaries.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        //getView一二级优化
        if(convertView == null){
            //反射出每行的布局
            convertView = inflater.inflate(R.layout.item,null);
            holder = new ViewHolder();
            holder.title = (TextView)convertView.findViewById(R.id.itme_title);
            holder.time =(TextView) convertView.findViewById(R.id.itme_time);
            holder.message = (TextView)convertView.findViewById(R.id.item_message);
            convertView.setTag(holder);
        }else {
            holder = (ViewHolder) convertView.getTag();
        }
        //获取当前行的实体类
        LifeDiary lifeDiary = lifeDiaries.get(position);

       if(MainActivity.KEYWORD == null){//判断搜索后状态，防止空指针
           holder.title.setText(lifeDiary.getTitle());
       }else {
           //设置高亮
           holder.title.setText(Utils.hightLightText(lifeDiary.getTitle(), MainActivity.KEYWORD));
       }
        holder.time.setText(Utils.getNomalTime(lifeDiary.getCreatetime()));
        //设置高亮
        if(MainActivity.KEYWORD == null){//判断搜索后状态，防止空指针
            holder.message.setText(lifeDiary.getMessage());
        }else{
            holder.message.setText(Utils.hightLightText(lifeDiary.getMessage(),MainActivity.KEYWORD));
        }
        //修复删除后添加，item还处于选中状态
        convertView.setBackgroundColor(Color.WHITE);
       /* holder.message.setText(lifeDiary.getMessage());*/
        return convertView;
    }

    public class ViewHolder{//ListView二级优化操作
        TextView title;
        TextView time;
        TextView message;
    }
}

